// Package dbservice
// @Author: zhangdi
// @File: clips
// @Version: 1.0.0
// @Date: 2023/5/25 11:47
package dbservice

import (
	"ideatools/application/constant"
	"ideatools/application/db/columns"
	"ideatools/application/db/dbdto"
	"ideatools/application/db/repository"
	"ideatools/application/db/sqllite"
	"ideatools/application/dto"
	"ideatools/application/pkgs/mylog"
	"ideatools/application/pkgs/utils"
	"ideatools/application/pkgs/where"
)

type ClipboardService struct {
	repo *repository.ClipboardRepository
}

func NewClipboardService() *ClipboardService {
	return &ClipboardService{
		repo: repository.NewClipboardRepository(sqllite.GetDb()),
	}
}

// CreateClipboard 创建一个工具
func (s *ClipboardService) CreateClipboard(DtoClipboardCreate *dbdto.ClipboardAdd) dto.RespData {

	err := s.repo.Create(DtoClipboardCreate)
	if err != nil {
		return dto.RespError(err.Error())
	}

	return dto.RespOk("创建完成", DtoClipboardCreate)
}

//func (s *ClipboardService) GetLastClipText() dto.RespData {
//	wheres := where.Format()
//	List, err := s.repo.FindList(wheres)
//	if err != nil {
//		return dto.RespError(err.Error())
//	}
//	return dto.RespOk("ok", List)
//
//}

// DelClipboard 删除
func (s *ClipboardService) DelClipboard(id int) dto.RespData {
	wheres := where.Format(where.Opt("id", "=", id))
	err := s.repo.DeleteByFieldValue(wheres)
	if err != nil {
		return dto.RespError(err.Error())
	}
	return dto.RespOk("ok", nil)

}

func (s *ClipboardService) GetListClipboardList(page, pageSize int) *dbdto.ClipboardSelect {
	wheres := where.Format()
	extra := &where.Extra{
		OrderByColumn: columns.ChatDialogID,
		OrderByDesc:   true,
		Limit:         pageSize,
		Offset:        (page - 1) * pageSize,
	}

	List, err := s.repo.FindListExtra(wheres, extra)
	if err != nil {
		mylog.Error(err.Error())
		return nil
	}
	var resList []*dbdto.ClipboardInfo
	for _, item := range List {
		temp := &dbdto.ClipboardInfo{}
		utils.DtoToEntity(item, temp)
		resList = append(resList, temp)
	}

	total, err := s.repo.GetTotalNum(wheres)
	result := &dbdto.ClipboardSelect{
		List:     resList,
		Total:    total,
		CurrPage: 0,
		PageSize: 0,
	}
	return result
}

func (s *ClipboardService) GetLastClipText(num int) []string {
	wheres := where.Format()
	extra := &where.Extra{
		OrderByColumn: columns.ClipboardId,
		OrderByDesc:   true,
		Limit:         num,
		Offset:        0,
	}
	list, err := s.repo.FindListExtra(wheres, extra)
	if err != nil {
		return nil
	}

	var res []string
	for _, clipboard := range list {
		res = append(res, clipboard.Content)
	}

	return res

}

// CheckMaxSave 检测是否超过最大保留条数
func (s *ClipboardService) CheckMaxSave() {

	//思路：先判断总数和保存条数，如果总数大于保存数，则求出差值（即要删除的条数），
	//根据差值按照asc查出所有数据，找到id最大的，小于该id都删除即可
	max := Conf().GetNumber(constant.ConfigKeyLeastMaxClipTexts)
	if max <= 0 {
		max = 1000
	}

	totalNum, err := s.repo.GetTotalNum(where.Format())
	if err != nil {
		mylog.Error("CheckMaxSave()" + err.Error())
		return
	}

	if totalNum <= int64(max) {
		return
	}

	delNum := totalNum - int64(max)
	list, err := s.repo.FindListExtra(where.Format(), &where.Extra{
		OrderByColumn: columns.ClipboardId,
		OrderByDesc:   false,
		Limit:         int(delNum),
		Offset:        0,
	})
	//得到最后一条id,小于该id的都删除
	if err != nil {
		mylog.Error("CheckMaxSave()2" + err.Error())
		return
	}
	lastId := list[len(list)-1].Id
	delWheres := where.Format(where.Opt(columns.ClipboardId, "<=", lastId))
	err = s.repo.DeleteByFieldValue(delWheres)
	if err != nil {
		mylog.Error("CheckMaxSave()3" + err.Error())
		return
	}

}
